//
//  ProductDetailLineController.m
//  FinancialProduct
//
//  Created by Stella on 2017/9/9.
//  Copyright © 2017年 maq. All rights reserved.
//
#import "MyAccountCell.h"
#import "CKPuslichTool.h"
#import "UIColor+NN.h"
#import "LineView.h"
#import "HandleNetProduct.h"
//#import "DBCharts.h"
#import "UserModel.h"
#import "MakeAppointmentController.h"
#import "Header.h"
#import "SVProgressHUD.h"
#import "HistoryRoseController.h"
#import "HandleNetProduct.h"
#import "myWebViewController.h"
#import "TKAlertCenter.h"
#import "DBHelper.h"
#import "XLineChartView.h"
#import "ProductDetailLineController.h"

@interface ProductDetailLineController ()
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UIView *redView;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *abcMode;
@property (weak, nonatomic) IBOutlet UILabel *topLeft;
@property (weak, nonatomic) IBOutlet UILabel *topMiddle;
@property (weak, nonatomic) IBOutlet UILabel *topRight;
@property (weak, nonatomic) IBOutlet UILabel *openTime;
@property (weak, nonatomic) IBOutlet UILabel *closeTime;
@property (weak, nonatomic) IBOutlet UILabel *hasTime;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *TableH;
@property (weak, nonatomic) IBOutlet UIView *picView;
@property(nonatomic,strong)NSArray *LineDataArray;
@property (weak, nonatomic) IBOutlet UILabel *Label1;
@property (weak, nonatomic) IBOutlet UILabel *Label2;
@property (weak, nonatomic) IBOutlet UILabel *labelMiddle;
@property (weak, nonatomic) IBOutlet UILabel *hasLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLa;
@property (weak, nonatomic) IBOutlet UILabel *nameMiddle;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *picViewH;
@property (weak, nonatomic) IBOutlet UIView *picMiddleView;
@property (weak, nonatomic) IBOutlet UILabel *line2;
@property (weak, nonatomic) IBOutlet UILabel *lineName;
@property (nonatomic, strong)NSArray *dataArray;
@property (weak, nonatomic) IBOutlet UITableView *bottomTable;

@property (weak, nonatomic) IBOutlet UIButton *makeBt;


@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableToBottom;

@end

@implementation ProductDetailLineController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"产品详情";
    self.TableH.constant=4*50+20;
    _dataArray=@[@"基本信息",@"个人认购提示",@"机构认购提示"];
    self.picMiddleView.hidden=YES;
    self.picViewH.constant=0;
    UIViewSetRadius(_makeBt, 25, 0, nil);
    self.bottomView.backgroundColor = [UIColor clearColor];
    if ([[UserModel getUser].Accountstatus intValue]==2) {
        //判断临时客户，去预约理财师
        self.tableToBottom.constant = 80;
        self.bottomView.hidden = NO;
    }else{
        self.tableToBottom.constant = 0;
        self.bottomView.hidden = YES;
    }
    [self initMyTopView];
    if (![_productTypeLevel1 isEqualToString:@"一级市场"] && ![_productModel.ProductType isEqualToString:@"C"]) {
        [self getLineDataWithSubId:self.productId];
    }
    
    
  
}


- (IBAction)makePoint:(id)sender {
    MakeAppointmentController *make = (MakeAppointmentController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Product" viewID:@"MakeAppointmentController"];
    [self.navigationController pushViewController:make animated:YES];
}


-(void)getLineDataWithSubId:(NSString *)subId{
    NSDictionary *params=@{@"AAAMethodName":@"InfodisclosureNetSelect",@"SubProductId":subId};
    [HandleNetProduct getListforParams:params Success:^(NSArray *data) {
        /**
         DocDate = "2016/7/29 0:00:00";
         IsSelect = No;
         Maximum = "55.34";
         Minimum = "-16.22";
         Net = "1.1512";
         Rose = "-6.71";
         SumNet = "1.1512";
         SumRose = "15.12";
         **/
        if (data.count>0) {
            self.LineDataArray=data;

            [self sortMyData];
            self.picMiddleView.hidden=NO;
            self.picViewH.constant=300;
            _dataArray=@[@"历史净值",@"基本信息",@"个人认购提示",@"机构认购提示"];
        }else{
            _dataArray=@[@"基本信息",@"个人认购提示",@"机构认购提示"];
            self.picMiddleView.hidden=YES;
            self.picViewH.constant=0;
        }
        [self.bottomTable reloadData];
        
    } Failure:^(NSString *errorInfo) {
        
    }];
}
-(void)sortMyData{
    self.line2.hidden=YES;
    self.lineName.hidden=YES;
    XLineChartView *chartView = [[XLineChartView alloc] initWithFrame:self.picView.bounds];
    chartView.xAssistLineColor=[UIColor whiteColor];//纵向辅助线颜色
    chartView.strokeLineWidth=1;//线条宽度
    chartView.coordColor=[UIColor lightGrayColor];
    chartView.coordWidth=0.5;//坐标轴颜色
    chartView.yLabNumber=5;//Y分块个数
    chartView.animationEnable=NO;
    chartView.chartType = XChartLineTypeCurve;//设置绘制类型为曲线
    chartView.showDot = NO;   //设置显示圆点
    chartView.gradientEnable = NO;  //设置启用渐变填充
    NSMutableArray *xTitles = [NSMutableArray array];
    NSMutableArray *yValues = [NSMutableArray array];
    
    for (UIView *vc in self.picView.subviews) {
        [vc removeFromSuperview];
    }
    if (self.LineDataArray.count==0) {
        return;
    }
    
    float max=[self.LineDataArray[0][@"Maximum"] floatValue];
    float min=[self.LineDataArray[0][@"Minimum"] floatValue];
    float sum=max-min;
    if (sum==0) {
        if ([self.LineDataArray[0][@"Reference"] isEqualToString:@"无"]) {
            self.line2.hidden=YES;
            self.lineName.hidden=YES;
        }else{
            self.line2.hidden=NO;
            self.lineName.hidden=NO;
            NSString *nameSS=[NSString stringWithFormat:@"%@增长率",self.LineDataArray[0][@"Reference"]];
            self.lineName.text=nameSS;
        }
        return;
    }
    float sizeH = sum/5;
    //    NSLog(@"sizeH==%d",sizeH);
    NSString *hh1=[NSString stringWithFormat:@"%.2f",min];
    NSString *hh2=[NSString stringWithFormat:@"%.2f",min+sizeH];
    NSString *hh3=[NSString stringWithFormat:@"%.2f",min+sizeH*2];
    NSString *hh4=[NSString stringWithFormat:@"%.2f",min+sizeH*3];
    NSString *hh5=[NSString stringWithFormat:@"%.2f",min+sizeH*4];
    NSString *hh6=[NSString stringWithFormat:@"%.2f",max];
    NSMutableArray *leftdataA = [NSMutableArray new];
    [leftdataA addObject:hh1];
    [leftdataA addObject:hh2];
    [leftdataA addObject:hh3];
    [leftdataA addObject:hh4];
    [leftdataA addObject:hh5];
    [leftdataA addObject:hh6];
    
    
    NSMutableArray* chartData = [NSMutableArray arrayWithCapacity:self.LineDataArray.count];
    NSMutableArray* chartData2 = [NSMutableArray arrayWithCapacity:self.LineDataArray.count];
    NSMutableArray* chartData3 = [NSMutableArray arrayWithCapacity:self.LineDataArray.count];
    NSArray* reversedArray = [[self.LineDataArray reverseObjectEnumerator] allObjects];
    for (int i=0; i<reversedArray.count; i++) {
        
        [chartData addObject:reversedArray[i][@"SumRose"]];
        [chartData2 addObject:reversedArray[i][@"Rose"]];
        [xTitles addObject:@""];
        NSDate *dateTime =  [DBHelper dateFromCustomString:reversedArray[i][@"DocDate"] format:@"yyyy/MM/dd HH:mm:ss"];
        NSString *time = [DBHelper stringFromCustomFormatDate:dateTime format:@"yyyy-MM-dd"];
        [chartData3 addObject:time];
    }
    [yValues addObject:chartData];
    NSArray *nameTitleArray=[NSArray array];
    NSArray *colorA = [NSArray array];
    if ([self.LineDataArray[0][@"Reference"] isEqualToString:@"无"]) {
        self.line2.hidden=YES;
        self.lineName.hidden=YES;
        colorA=@[[UIColor colorWithHexString:@"#65AFF7"]];
        nameTitleArray=@[@"产品净值增长率"];
    }else{
        self.line2.hidden=NO;
        self.lineName.hidden=NO;
        NSString *nameSS=[NSString stringWithFormat:@"%@增长率",self.LineDataArray[0][@"Reference"]];
        self.lineName.text=nameSS;
        [yValues addObject:chartData2];
        colorA=@[[UIColor colorWithHexString:@"#65AFF7"],[UIColor blackColor]];
        nameTitleArray=@[@"产品净值增长率",nameSS];
    }
    
    
    chartView.chartColors=colorA;
    chartView.xTitles = chartData3;    //设置X
    chartView.yValuesArray = yValues;  //设置Y
    chartView.yNameArr=leftdataA;
    chartView.xDateArrays=chartData3;
    chartView.dataNameArr=nameTitleArray;
    chartView.markerLineColor=[UIColor colorWithHexString:@"#BB3535"];
    chartView.scaleType=XChartViewScaleTypeNone;
    
    [self.picView addSubview:chartView];
    [chartView strokeChart];  //绘制曲线
}


-(void)initMyTopView{
    UIViewSetRadius(self.redView, 60, 5, [UIColor colorWithHexString:@"F0ABAB"]);
    if ([_productModel.ProductType isEqualToString:@"C"]) {
        LineView *lineView=[[LineView alloc] initWithFrame:CGRectMake(0, 0, 120, 120) lineCount:3];
        [self.bgView addSubview:lineView];
        
        self.topLeft.text=@"";
        self.topRight.text=@"";
        self.Label1.text=@"";
        self.Label2.text=@"";
        self.labelMiddle.text=@"可售规模";
        self.topMiddle.text=_productModel.SaleAmount;
        self.timeLa.text=@"产品成立日";
        self.openTime.text=self.productModel.PurchaseOpenDay;
        self.hasLabel.text=@"产品期限";
        self.hasTime.text=_productModel.ProductPeriod;
    }else if ([_productModel.ProductType isEqualToString:@"D"]) {
        
        LineView *lineView=[[LineView alloc] initWithFrame:CGRectMake(0, 0, 120, 120) lineCount:2];
        [self.bgView addSubview:lineView];
        
        self.topLeft.text=@"";
        self.Label1.text=@"";
        self.hasLabel.text=@"";
        self.hasTime.text=@"";
        self.topMiddle.text=@"";
        self.labelMiddle.text=@"";
        
        self.timeLa.text=@"产品开放日";
        self.openTime.text=_productModel.PurchaseOpenDay;
        self.topRight.text=_productModel.SaleAmount;
        
        
    }else{
        LineView *lineView=[[LineView alloc] initWithFrame:CGRectMake(0, 0, 120, 120) lineCount:4];
        [self.bgView addSubview:lineView];
        
        self.timeLa.text=@"产品开放日";
        self.topMiddle.text=@"";
        self.labelMiddle.text=@"";
        self.topLeft.text=_productModel.ExpectedRate;
        self.topRight.text=_productModel.SaleAmount;
        self.openTime.text=_productModel.PurchaseOpenDay;
        self.hasTime.text=_productModel.ProductPeriod;
    }
    self.name.text=self.nameMiddle.text=_productModel.SubProductName;
    self.abcMode.text=[NSString stringWithFormat:@"%@类资产",_productModel.ABCModel];
    self.closeTime.text=[NSString stringWithFormat:@"预约截止日期：%@",_productModel.ClosingDate];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50
    ;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return self.dataArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MyAccountCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MyAccountCell" forIndexPath:indexPath];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.accessoryType=UITableViewCellAccessoryNone;
 
    cell.NameLabel.text=self.dataArray[indexPath.row];
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (self.picMiddleView.hidden) {
        switch (indexPath.row) {
     
            case 0://基本信息
            {
                
                [self getURLWith:@"EssentialInformation"];
            }
                break;
            case 1://个人认购提示
            {
                
                [self getURLWith:@"Personage"];
            }
                break;
            case 2://机构认购提示
            {
                [self getURLWith:@"InstitutionalSubscription"];
            }
                break;
                
            default:
                break;
        }
    }else{
        switch (indexPath.row) {
            case 0://历史净值
            {
                
                HistoryRoseController *vc=(HistoryRoseController *)[CKPuslichTool getViewControllerFromStroyBoard:@"My" viewID:@"HistoryRoseController"];
                vc.dataArray=self.LineDataArray;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 1://基本信息
            {
                
                [self getURLWith:@"EssentialInformation"];
            }
                break;
            case 2://个人认购提示
            {
                
                [self getURLWith:@"Personage"];
            }
                break;
            case 3://机构认购提示
            {
                [self getURLWith:@"InstitutionalSubscription"];
            }
                break;
                
            default:
                break;
        }
    }


}
-(void)getURLWith:(NSString *)type{
    NSLog(@"self.productModel.SubProductID==%@",self.productModel.SubProductID);
    NSDictionary *params=@{@"AAAMethodName":type,@"SubProductId":self.productId};
    [HandleNetProduct getDetailForParams:params Success:^(NSDictionary *data) {
        NSString *paths=data[@"Path"];
   
        myWebViewController *vc=(myWebViewController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Setting" viewID:@"myWebViewController"];
        if ([type isEqualToString:@"EssentialInformation"]) {
            vc.title=@"基本信息";
        }else if ([type isEqualToString:@"Personage"]) {
            vc.title=@"个人认购提示";
        }else{
            vc.title=@"机构认购提示";
        }
        
        
        vc.urlString=paths;
        
        
        [self.navigationController pushViewController:vc animated:YES];
        

    } Failure:^(NSString *errorInfo) {
      
        [[TKAlertCenter defaultCenter]postAlertWithMessage:errorInfo];
    }];

}


@end
